package com.linQing.waterWork.service.sql.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linQing.waterWork.mapper.sql.SwsEventjkhistoryMapper;
import com.linQing.waterWork.modle.dto.PageEventHistoryDto;
import com.linQing.waterWork.modle.entity.SwsEventjkhistory;
import com.linQing.waterWork.modle.export.EventHistoryExport;
import com.linQing.waterWork.modle.vo.EventHistoryListVo;
import com.linQing.waterWork.service.sql.SwsEventjkhistoryService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【Sws_EventJKHistory】的数据库操作Service实现
 * @createDate 2024-04-23 14:20:34
 */

@Service
public class SwsEventjkhistoryServiceImpl extends ServiceImpl<SwsEventjkhistoryMapper, SwsEventjkhistory>
        implements SwsEventjkhistoryService {

    @Autowired
    private SwsEventjkhistoryMapper mapper;

    @Override
    public List<EventHistoryListVo> selectEventHistory(PageEventHistoryDto pageEventHistoryDto) {
        return mapper.selectEventHistory(pageEventHistoryDto);
    }

    static class CustomSheetWriteHandler implements RowWriteHandler {

        // 定义一个布尔变量，用于控制是否初始化
        private boolean init = true;

        /**
         * 行创建前的执行方法
         *
         * @param writeSheetHolder sheet
         * @param writeTableHolder table
         * @param rowIndex         行索引
         * @param relativeRowIndex 执行行索引
         * @param isHead           表头
         */
        @Override
        public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {
            // 如果是第一次创建行，则进行初始化
            if (init) {
                // 修改存储头部及对应字段信息的 map，将其中的内容均右移一位，给新增的序列号预留为第一列
                ExcelWriteHeadProperty excelWriteHeadProperty = writeSheetHolder.excelWriteHeadProperty();
                Map<Integer, Head> headMap = excelWriteHeadProperty.getHeadMap();
                int size = headMap.size();
                for (int current = size; current > 0; current--) {
                    int previous = current - 1;
                    headMap.put(current, headMap.get(previous));
                }
                // 空出第一列
                headMap.remove(0);
                // 只需要修改一次 map 即可，故使用 init 变量进行控制
                init = false;
            }
        }


        /**
         * 行创建后的执行方法
         *
         * @param writeSheetHolder
         * @param writeTableHolder
         * @param row
         * @param relativeRowIndex
         * @param isHead
         */
        @Override
        public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
            //设置sheet名称
            Sheet sheet = writeSheetHolder.getSheet();
            Workbook workbook = sheet.getWorkbook();
            Font font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 12);

// 创建字体，并设置加粗
            Font font1 = workbook.createFont();
            font1.setBold(true);

// 创建单元格样式，并设置字体和背景颜色
            CellStyle style = workbook.createCellStyle();
            style.setFont(font1);

// 设置背景颜色为灰色，这里使用的是 RGB 值
            style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
// 应用这个样式到标题行（假设标题行是第一行）
            Row titleRow = sheet.getRow(0);
            for (int i = 0; i < titleRow.getLastCellNum(); i++) {
                Cell cell = titleRow.getCell(i);
                if (cell == null) {
                    cell = titleRow.createCell(i);
                }
                cell.setCellStyle(style);

            }
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setFont(font);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderRight(BorderStyle.THIN);

            for (Cell cell : row) {
                cell.setCellStyle(cellStyle);
                if (cell.getColumnIndex() == 0) {
                    CellStyle cellStyle1 = workbook.createCellStyle();
                    cellStyle1.setAlignment(HorizontalAlignment.CENTER);
                    cellStyle1.setFont(font);
                    cellStyle1.setBorderTop(BorderStyle.THIN);
                    cellStyle1.setBorderBottom(BorderStyle.THIN);
                    cellStyle1.setBorderLeft(BorderStyle.THIN);
                    cellStyle1.setBorderRight(BorderStyle.THIN);
                    cell.setCellStyle(cellStyle1);
                    continue;
                }
                if (cell.getColumnIndex() == 2) {
                    CellStyle cellStyle2 = workbook.createCellStyle();
                    cellStyle2.setAlignment(HorizontalAlignment.LEFT);
                    cellStyle2.setFont(font);
                    cellStyle2.setBorderTop(BorderStyle.THIN);
                    cellStyle2.setBorderBottom(BorderStyle.THIN);
                    cellStyle2.setBorderLeft(BorderStyle.THIN);
                    cellStyle2.setBorderRight(BorderStyle.THIN);
                    cell.setCellStyle(cellStyle2);
                    continue;
                }
                // 如果是日期或时间值，设置单元格的日期格式
                if (cell.getCellType() == CellType.NUMERIC) {
                    double numericCellValue = cell.getNumericCellValue();
                    // 检查序列号是否落在合理范围内（示例范围，根据需要调整）
                    if (numericCellValue > 0) {
                        // 为单元格应用日期时间格式
                        DataFormat dataFormat = workbook.createDataFormat();
                        // 设置日期时间格式，根据你的需求调整格式字符串
                        short dateFormatIndex = dataFormat.getFormat("yyyy-MM-dd HH:mm:ss");
                        cellStyle.setDataFormat(dateFormatIndex);
                        cell.setCellStyle(cellStyle);
                    }
                }
            }
        }

        /**
         * 行创建后的执行方法
         *
         * @param writeSheetHolder sheet
         * @param writeTableHolder table
         * @param row              行
         * @param relativeRowIndex 执行行索引
         * @param isHead           表头
         */
        @Override
        public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
            // 在行创建完成后添加序号列
            Cell cell = row.createCell(0);
            int rowNum = row.getRowNum();
            if (rowNum == 0) {
                // 如果是第一行，则将单元格的值设置为“序号”
                cell.setCellValue("序号");
            } else {
                // 如果不是第一行，则将单元格的值设置为当前行号
                cell.setCellValue(rowNum);
            }
        }
    }


    public void export(PageEventHistoryDto pageEventHistoryDto, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("报警信息表格", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
        pageEventHistoryDto.setPageNum(1);
        pageEventHistoryDto.setPageSize(Integer.MAX_VALUE);
        List<EventHistoryListVo> eventHistoryListVos = mapper.selectEventHistory(pageEventHistoryDto);
        List<EventHistoryExport> collect = eventHistoryListVos.stream().map(eventHistoryListVo -> {
                    EventHistoryListVo v = eventHistoryListVo;
                    EventHistoryExport eventHistoryExport = new EventHistoryExport();
                    BeanUtils.copyProperties(v, eventHistoryExport);
//                    eventHistoryExport.setRowNumber(i + 1);
                    return eventHistoryExport;
                })
                .collect(Collectors.toList());
        CustomSheetWriteHandler customSheetWriteHandler = new CustomSheetWriteHandler();
        EasyExcel.write(response.getOutputStream(), EventHistoryExport.class)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(customSheetWriteHandler)
                .sheet(0, "报警信息")
                .doWrite(collect);
    }

}




